import React, { useEffect, useMemo, useState } from 'react'
import { Popup, TextArea, PickerView, CascadePickerView, Toast } from 'antd-mobile'
import "@/assets/css/hlthArchives.scss"
import { 
    diseaseList, 
    allergyList, 
    habitList, 
    targetMap, 
    titList, 
    txtAreaStyle, 
    genderStyle, 
    dateStyle, 
    weightStyle, 
    smokeStyle,
    drinkAmountMap } from "@/utils/historyUtil"
import { fromJS } from "immutable"

import HeadBack from "@/components/HeadBack"

import { getUsername } from "@/utils/storageUtil"

import { findUserHlthProfile, addOrUpdateUserHlthProfile } from "@/utils/dataUtil"

import unitImg from "@/assets/images/hospital/unit.png"
import arrowImg from "@/assets/images/hospital/arrow.png"
import { useNavigate } from 'react-router-dom'

export default function HlthArchives() {

    const navigate = useNavigate();

    const [diseaseLists, setDiseaseLists] = useState(fromJS(diseaseList))
    const [hlthDiseaseVal, setHlthDiseaseVal] = useState("");

    const [allergyLists, setAllergyLists] = useState(fromJS(allergyList))
    const [allergyVal, setAllergyVal] =  useState("");

    const [habitLists, setHabitLists] = useState(fromJS(habitList))
    const [habitVal, setHabitVal] = useState("");

    //弹出层是否展示
    const [visible, setVisible] = useState(false);
    //点击哪一个索引
    const [count, setCount] = useState(0);


    //性别 受控的
    const [gerders, setGenders] = useState([]);
    //性别值
    const [gerder, setGender] = useState(gerders.length !== 0 ? gerders[0] : "");

    //日期受控
    const [dateValue, setDateValue] = useState(["2000", "01", "01"]);
    //日期值
    const [dateVal, setDateVal] = useState(dateValue.join("-"));

    //身高受控
    const [statureValue, setStatureValue] = useState([160]);
    //身高值
    const [statureVal, setStatureVal] = useState(statureValue[0]);

    //体重受控
    const [weightValue, setWeightValue] = useState([55]);
    //体重值
    const [weightVal, setWeightVal] = useState(weightValue[0]);

    //血型受控
    const [bloodValue, setBloodValue] = useState([]);
    //血型值
    const [bloodVal, setBloodVal] = useState(bloodValue.length !== 0 ? bloodValue[0] : "");

    //吸烟受控
    const [smokeValue, setSmokeValue] = useState([]);
    //吸烟值
    const [smokeVal, setSmokeVal] = useState(smokeValue.join("、"));

    //饮酒受控
    const [drinkValue, setDrinkValue] = useState([]);
    //饮酒值
    const [drinkVal, setDrinkVal] = useState(drinkValue.join("、"));

    useEffect(() => {
        //判断赋初始值
        findUserHlthProfile().then(res => {
            if(res.status === 1 && res.data && JSON.stringify(res.data) !== '{}') {
                //性别
                setGenders([res.data.gender]);
                setGender(res.data.gender);

                //出生日期
                setDateValue(res.data.birthday.split("-"));
                setDateVal(res.data.birthday);

                //身高
                if(res.data.height) {
                    setStatureValue([res.data.height])
                    setStatureVal(res.data.height);
                }

                //体重
                if(res.data.weight) {
                    setWeightValue([res.data.weight]);
                    setWeightVal(res.data.weight);
                }

                // 血型
                if(res.data.illProfile && res.data.illProfile.bloodType) {
                    setBloodValue([res.data.illProfile.bloodType]);
                    setBloodVal(res.data.illProfile.bloodType);
                }

                //疾病史
                if(res.data.illProfile && res.data.illProfile.illness) {
                    setDiseaseLists((current) => {
                        current.forEach((item, index) => {
                            res.data.illProfile.illness.forEach((val) => {
                                if(item.get("label") === val) {
                                    current = current.set(index, item.set("click", true));
                                }
                            })
                        })
                        return current;
                    })
                }

                //疾病史 补充
                if(res.data.illProfile && res.data.illProfile.illnessSupp) {
                    setHlthDiseaseVal(res.data.illProfile.illnessSupp);
                }

                //药物过敏
                if(res.data.illProfile && res.data.illProfile.drugAllergies) {
                    setAllergyLists((current) => {
                        current.forEach((item, index) => {
                            res.data.illProfile.drugAllergies.forEach((val) => {
                                if(item.get("label") === val) {
                                    current = current.set(index, item.set("click", true));
                                }
                            })
                        })
                        return current;
                    })
                }

                //药物过敏 补充
                if(res.data.illProfile && res.data.illProfile.drugAllergiesSupp) {
                    setAllergyVal(res.data.illProfile.drugAllergiesSupp);
                }

                //个人习惯
                if(res.data.illProfile && res.data.illProfile.badHabits) {
                    setHabitLists((current) => {
                        current.forEach((item, index) => {
                            res.data.illProfile.badHabits.forEach((val) => {
                                if(item.get("label") === val) {
                                    current = current.set(index, item.set("click", true));
                                }
                            })
                        })
                        return current;
                    })
                }

                //个人习惯 补充
                if(res.data.illProfile && res.data.illProfile.badHabitsSupp) {
                    setHabitVal(res.data.illProfile.badHabitsSupp);
                }

                //吸烟史
                if(res.data.illProfile && res.data.illProfile.smoking) {
                    const { is, age, dayNum } = res.data.illProfile.smoking;
                    setSmokeValue([is, age, dayNum]);
                    setSmokeVal(`${is === 1 ? '是' : '否'}、${age}、${dayNum}`)
                }

                //饮酒史
                if(res.data.illProfile && res.data.illProfile.drinking) {
                    const { is, age, types } = res.data.illProfile.drinking;
                    if(is === 0) {
                        setDrinkValue([0, '--', '--', '--']);
                        setDrinkVal("否、--、--、--")
                    } else {
                        setDrinkValue([1, age, types.length > 1 ? '以上都有' : types[0], drinkAmountMap[is.toString()]]);
                        setDrinkVal(`${is === 0 ? '否' : '是'}、${age}、${types.length > 1 ? '以上都有' : types[0]}、${drinkAmountMap[is.toString()]}`);
                    }
                }
            }
        })
    }, [])

    //点击每一个item的值，判断要弹出哪一个弹出层
    const clickItem = (index) => {
        setCount(index);
        setVisible(true);
    }

    //点击每一个选择框的取消按钮
    const clickCancel = () => {
        setVisible(false);
    }

    //点击每一个选择框的确定按钮
    const clickConfirm = () => {
        switch(count) {
            case 0:
                setGender(gerders[0]);
                break;
            case 1:
                setDateVal(dateValue.join("-"));
                break;
            case 2:
                setStatureVal(statureValue[0]);
                break;
            case 3:
                setWeightVal(weightValue[0]);
                break;
            case 4:
                setBloodVal(bloodValue[0]);
                break;
            case 5:
                const curSmokes = smokeValue.concat();
                curSmokes[0] = curSmokes[0] === 0 ? '否' : '是';
                setSmokeVal(curSmokes.join("、"));
                break;
            case 6:
                const curDrinks = drinkValue.concat();
                curDrinks[0] = curDrinks[0] === 0 ? '否' : '是';
                setDrinkVal(curDrinks.join("、"));
                break;
        }
        setVisible(false);
    }




    //值的改变
    const valChanger = (val, index) => {
        switch(index) {
            case 0:
                setGenders(val);
                break;
            case 1:
                setDateValue(val);
                break;
            case 2:
                setStatureValue(val);
                break;
            case 3:
                setWeightValue(val);
                break;
            case 4:
                setBloodValue(val);
                break;
            case 5:
                setSmokeValue(val);
                break;
            case 6:
                setDrinkValue(val);
                break;
        }
        
    }
    //性别值的变化
    const genderChanger = (val) => {
        valChanger(val, 0);
    }
    
    //日期值的变化
    const dateChanger = (val) => {
        valChanger(val, 1);
    }
    
    //身高值的变化
    const statureChanger = (val) => {
        valChanger(val, 2);
    }
    
    //体重值的变化
    const weightChanger = (val) => {
        valChanger(val, 3);
    }
    
    //血型值的变化
    const bloodChanger = (val) => {
        valChanger(val, 4);
    }
    
    //吸烟值的变化
    const smokeChanger = (val) => {
        valChanger(val, 5);
    }
    
    //饮酒值的变化
    const drinkChanger = (val) => {
        valChanger(val, 6);
    }
    
    //item的点击事件公共方法
    const publicItemMethod = (index, status, list, setList, have = true) => {
        //判断当前是否为暂无，是还未选中则选中其他置为未选中
        if(index === 0 && status === false && have === true) {
            const current = list.map((item, i) => item.set("click", i === 0 ? true : false));
            setList(current);
            return;
        }
        //点击非暂无按钮，判断暂无是否选中，选中则置为未选中
        if(index !== 0 && list.get(0).get("click") === true && have === true) {
            const current = list.map((item, i) => {
                return item.set("click", i === 0 ? false : i === index ? !status : item.get("click"));
            });
            setList(current);
            return;
        }
        // 正常点击
        setList((item) => item.set(index, item.get(index).set("click", !status)));
    }

    //点击疾病史的item
    const clickDiseaseItem = (index, status) => {
        publicItemMethod(index, status, diseaseLists, setDiseaseLists);
    }

    //点击药物过敏的item
    const clickAllergyItem = (index, status) => {
        publicItemMethod(index, status, allergyLists, setAllergyLists);
    }

    //点击个人习惯
    const clickHabitItem = (index, status) => {
        publicItemMethod(index, status, habitLists, setHabitLists, false);
    }

    //按钮是否可点击
    const disabledBtn = useMemo(() => typeof gerder === "number" && typeof dateVal === "string", [gerder, dateVal])

    //新建和修改的响应
    const publicResponse = (res) => {
        if(res.status === 1) {
            //添加成功
            Toast.show({
                content: "保存成功",
                position: 'bottom'
            });
            const timeout = setTimeout(() => {
                clearTimeout(timeout);
                navigate(-1);
            }, 1000);
        } else {
            Toast.show({
                content: `${res.msg}`,
                position: 'center'
            });
        }
    }

    //点击保存按钮
    const clickSubmitBtn = () => {
        if(!disabledBtn) {return;}

        let param = {
            gender: gerder,
            birthday: dateVal,
            height: statureVal,
            weight: weightVal,
            illProfile: {
                bloodType: bloodVal,
                illness: diseaseLists.filter((item) => item.get("click") === true).map((item) => item.get("label")).toJS(),
                illnessSupp: hlthDiseaseVal,
                drugAllergies: allergyLists.filter((item) => item.get("click") === true).map((item) => item.get("label")).toJS(),
                drugAllergiesSupp: allergyVal,
                badHabits: habitLists.filter((item) => item.get("click") === true).map((item) => item.get("label")).toJS(),
                badHabitsSupp: habitVal,
                smoking: {
                    is: smokeValue.length !== 0 && smokeValue[0],
                    age: smokeValue.length !== 0 && smokeValue[1],
                    dayNum: smokeValue.length !== 0 && smokeValue[2]
                },
                drinking: {
                    is: drinkValue.length !== 0 ? (drinkValue[0] === 0 ? 0 : drinkAmountMap[drinkValue[3]]) : null,
                    age: drinkValue.length !== 0 && drinkValue[1],
                    types: drinkValue.length !== 0 ? (drinkValue[2] === '以上都有' ? ['白酒', '啤酒', '红酒'] : [drinkValue[2]]) : []
                }
            }
        }

        addOrUpdateUserHlthProfile(param).then(res => {
            publicResponse(res);
        })
    }



    return (
        <div className="hlthContainer">

            <HeadBack background={"#FFFFFF"} backTit={""}  isHome="back"></HeadBack>

            {/* 用户的基本信息盒子 */}
            <div className='hlthInfoBox'>

                {/* 姓名 */}
                <div className='hlthUsername'>
                    <div className='hlthNameLeft'>
                        <img className='hlthNameUnit' alt='' src={unitImg} />姓名
                    </div>
                    {/* 姓名输入框 */}
                    <div className='hlthNameRight hlthGenderTxt'>{getUsername()}</div>
                </div>

                {/* 性别 */}
                <div className='hlthUsername'>
                    <div className='hlthNameLeft'>
                        <img className='hlthNameUnit' alt='' src={unitImg} />性别
                    </div>
                    {/* 姓名输入框 */}
                    <div className='hlthGenderRight' onClick={() => clickItem(0)}>
                        <div className='hlthGenderTxt'>{ gerder === 1 ? '男' : gerder === 2 ? '女' : '' }</div>
                        <img className='hlthGenderIcon' alt='' src={arrowImg} />
                    </div>
                </div>

                {/* 出生日期 */}
                <div className='hlthUsername'>
                    <div className='hlthNameLeft'>
                        <img className='hlthNameUnit' alt='' src={unitImg} />出生日期
                    </div>
                    {/* 姓名输入框 */}
                    <div className='hlthGenderRight' onClick={() => clickItem(1)}>
                        <div className='hlthGenderTxt'>{dateVal}</div>
                        <img className='hlthGenderIcon' alt='' src={arrowImg} />
                    </div>
                </div>

                {/* 身高 */}
                <div className='hlthUsername'>
                    <div className='hlthNameLeft'>身高</div>
                    {/* 姓名输入框 */}
                    <div className='hlthGenderRight' onClick={() => clickItem(2)}>
                        <div className='hlthGenderTxt'>{statureVal}cm</div>
                        <img className='hlthGenderIcon' alt='' src={arrowImg} />
                    </div>
                </div>

                {/* 体重 */}
                <div className='hlthUsername'>
                    <div className='hlthNameLeft'>体重</div>
                    {/* 姓名输入框 */}
                    <div className='hlthGenderRight' onClick={() => clickItem(3)}>
                        <div className='hlthGenderTxt'>{weightVal}kg</div>
                        <img className='hlthGenderIcon' alt='' src={arrowImg} />
                    </div>
                </div>

                {/* 血型 */}
                <div className='hlthUsername'>
                    <div className='hlthNameLeft'>血型</div>
                    {/* 姓名输入框 */}
                    <div className='hlthGenderRight' onClick={() => clickItem(4)}>
                        <div className='hlthGenderTxt'>{bloodVal}</div>
                        <img className='hlthGenderIcon' alt='' src={arrowImg} />
                    </div>
                </div>
            </div>

            {/* 药物史和疾病史和个人习惯 */}
            <div className='hlthHistoryBox'>
                
                {/* 疾病史 */}
                <div className='hlthDiseaseBox'>
                    <div className='hlthDiseaseTit'>疾病史</div>

                    <div className='hlthDiseaseUl'>
                        {
                            diseaseLists.map((item, index) => (<div className={`hlthDiseaseLi ${item.get("click") && 'hlthDiseaseLiCur'}`} onClick={() => clickDiseaseItem(index, item.get("click"))} key={index}>{item.get("label")}</div>))
                        }
                        
                    </div>

                    <div className='hlthDiseaseTxt'>
                        <TextArea
                            value={hlthDiseaseVal}
                            className='hlthDiseaseArea'
                            showCount
                            maxLength={20}
                            onChange={setHlthDiseaseVal}
                            placeholder='请输入补充内容'
                            style={txtAreaStyle}
                            />
                    </div>
                </div>

                {/* 过敏史 */}
                <div className='hlthDiseaseBox'>
                    <div className='hlthDiseaseTit hlthAllergy'>药物过敏</div>

                    <div className='hlthDiseaseUl'>
                        {
                            allergyLists.map((item, index) => (<div className={`hlthDiseaseLi ${item.get("click") && 'hlthDiseaseLiCur'}`} onClick={() => clickAllergyItem(index, item.get("click"))} key={index}>{item.get("label")}</div>))
                        }
                        
                    </div>

                    <div className='hlthDiseaseTxt'>
                        <TextArea
                            value={allergyVal}
                            showCount
                            className='hlthDiseaseArea'
                            maxLength={20}
                            onChange={setAllergyVal}
                            placeholder='请输入补充内容'
                            style={txtAreaStyle}
                            />
                    </div>
                </div>


                {/* 个人习惯 */}
                <div className='hlthDiseaseBox hlthhabitBox'>
                    <div className='hlthDiseaseTit hlthAllergy'>个人习惯</div>

                    <div className='hlthDiseaseUl'>
                        {
                            habitLists.map((item, index) => (<div className={`hlthDiseaseLi ${item.get("click") && 'hlthDiseaseLiCur'}`} onClick={() => clickHabitItem(index, item.get("click"))} key={index}>{item.get("label")}</div>))
                        }
                        
                    </div>

                    <div className='hlthDiseaseTxt'>
                        <TextArea
                            value={habitVal}
                            className='hlthDiseaseArea'
                            onChange={setHabitVal}
                            showCount
                            maxLength={20}
                            placeholder='请输入补充内容'
                            style={txtAreaStyle}
                            />
                    </div>
                </div>

            </div>


            {/* 吸烟史和饮酒史 */}
            <div className='hlthInfoBox hlthWineBox'>
                {/* 吸烟史 */}
                <div className='hlthUsername'>
                    <div className='hlthNameLeft'>吸烟史</div>
                    <div className='hlthGenderRight' onClick={() => clickItem(5)}>
                        <div className='hlthGenderTxt'>{smokeVal}</div>
                        <img className='hlthGenderIcon' alt='' src={arrowImg} />
                    </div>
                </div>

                {/* 饮酒史 */}
                <div className='hlthUsername'>
                    <div className='hlthNameLeft'>饮酒史</div>
                    <div className='hlthGenderRight' onClick={() => clickItem(6)}>
                        <div className='hlthGenderTxt'>{drinkVal}</div>
                        <img className='hlthGenderIcon' alt='' src={arrowImg} />
                    </div>
                </div>
            </div>



            {/* 保存按钮 */}
            <div className='hlthSaveBox'>
                <div className={`hlthSaveBtn ${disabledBtn && 'hlthSaveBtnCur'}`} onClick={clickSubmitBtn}>保存</div>
            </div>



            {/* 性别的弹出框 */}
            <Popup visible={visible} bodyStyle={{"backgroundColor": "transparent"}} onMaskClick={clickCancel}>
                <div className='hlthGenderModel'>
                    <div className={`hlthGenderBox ${count === 1 && 'hlthDateBox'} ${count !== 0 && count !== 1 &&'hlthStatureBox'}`}>
                        {/* 标题 */}
                        <div className='hlthGenderTit'>{titList[count]}</div>
                        <div className={`hlthSmokeUl ${count !== 5 && 'popHidden'}`}>
                            <div className='hlthSmokeLi'>是否吸烟</div>
                            <div className='hlthSmokeLi'>烟龄</div>
                            <div className='hlthSmokeLi'>每天数量</div>
                        </div>
                        <div className={`hlthSmokeUl ${count !== 6 && 'popHidden'}`}>
                            <div className='hlthSmokeLi'>是否饮酒</div>
                            <div className='hlthSmokeLi'>酒龄</div>
                            <div className='hlthSmokeLi'>主要酒类</div>
                            <div className='hlthSmokeLi'>饮用量</div>
                        </div>
                        {/* 选择性别 */}
                        <PickerView className={`popGender ${count !== 0 && 'popHidden'}`} value={gerders} onChange={genderChanger} columns={targetMap.genderColumns} style={genderStyle} />
                        <CascadePickerView className={`popDate ${count !== 1 && 'popHidden'}`} value={dateValue} onChange={dateChanger} options={targetMap.totalDate}  style={dateStyle} />
                        <PickerView className={`popGender popStature ${count !== 2 && 'popHidden'}`} value={statureValue} onChange={statureChanger} columns={targetMap.statureList} style={weightStyle} />
                        <PickerView className={`popGender popWeight ${count !== 3 && 'popHidden'}`} value={weightValue} onChange={weightChanger} columns={targetMap.weightList} style={weightStyle} />
                        <PickerView className={`popGender ${count !== 4 && 'popHidden'}`} value={bloodValue} onChange={bloodChanger} columns={targetMap.bloodColumns} style={weightStyle} />
                        <CascadePickerView className={`popGender popSmoke ${count !== 5 && 'popHidden'}`} value={smokeValue} onChange={smokeChanger} options={targetMap.smokeList} style={smokeStyle} />
                        <CascadePickerView className={`popGender popSmoke ${count !== 6 && 'popHidden'}`} value={drinkValue} onChange={drinkChanger} options={targetMap.drinkList} style={smokeStyle} />
                        {/* 按钮 */}
                        <div className='hlthGenderFoot'>
                            <div className='hlthGenderCancel' onClick={clickCancel}>取消</div>
                            <div className='hlthGenderCancel hlthGenderConfirm' onClick={clickConfirm}>确定</div>
                        </div>
                    </div>
                </div>
            </Popup>

            
        </div>
    )
}
